<template>
  <div class="ticket-manage">
    <el-card shadow="never" class="mb-3">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <el-icon><Tickets /></el-icon>
          <span class="text-lg font-bold">工单管理</span>
        </div>
        <el-button type="primary" @click="onCreateTicket">
          <el-icon><Plus /></el-icon>新建工单
        </el-button>
      </div>
    </el-card>
    <ticket-filter-bar
      :filters="filters"
      :assignees="assignees"
      @change="onFilterChange"
      class="mb-3"
    />
    <ticket-table
      :tickets="filteredTickets"
      @view="onViewTicket"
      @edit="onEditTicket"
      @delete="onDeleteTicket"
      @selection-change="onSelectionChange"
    />
    <template v-if="selectedTickets.length">
      <el-card class="mb-3" style="background:#f7f8fa;">
        <div class="flex items-center gap-2">
          <span>已选中 {{ selectedTickets.length }} 项</span>
          <!-- <el-button size="small" @click="onBatchAssign">批量分配</el-button> -->
          <el-button size="small" @click="onBatchClose">批量关闭</el-button>
          <el-button size="small" @click="onBatchExport">批量导出</el-button>
          <el-button size="small" @click="selectedTickets = []">清空选择</el-button>
        </div>
      </el-card>
    </template>
    <el-pagination
      class="mt-4 flex justify-center"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredTickets.length"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      v-model:current-page="page"
    />
    <ticket-detail-dialog
      v-if="showDetailDialog"
      :ticket="currentTicket"
      :quick-replies="quickReplies"
      :knowledge-base="knowledgeList.value"
      :categories="categories.value"
      @close="showDetailDialog = false"
    />
    <TicketEditDialog
      v-if="showEditDialog"
      :ticket="editTicket"
      :assignees="assignees"
      @save="onSaveTicket"
      @close="showEditDialog = false"
    />
    <!-- 批量分配客服弹窗 - 已隐藏 -->
    <!-- <TicketBatchAssignDialog
      :visible="showBatchAssign"
      :assignees="assignees"
      @confirm="onBatchAssignConfirm"
      @close="showBatchAssign = false"
    /> -->
    <TicketBatchExportDialog
      :visible="showBatchExport"
      :fields="exportFields"
      @confirm="onBatchExportConfirm"
      @close="showBatchExport = false"
    />
    <!-- 预留新建/编辑弹窗 -->
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { tickets as mockTickets, quickReplies, assignees } from '@/mock/mock-tickets'
import { knowledgeList, categories } from '@/mock/knowledge'
import TicketFilterBar from './TicketFilterBar.vue'
import TicketTable from './TicketTable.vue'
import TicketDetailDialog from './TicketDetailDialog.vue'
import TicketEditDialog from './TicketEditDialog.vue'
// import TicketBatchAssignDialog from './TicketBatchAssignDialog.vue'
import TicketBatchExportDialog from './TicketBatchExportDialog.vue'
import * as XLSX from 'xlsx'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Tickets } from '@element-plus/icons-vue'

const page = ref(1)
const pageSize = 10
const filters = ref({
  type: '',
  priority: '',
  status: '',
  assignee: '',
  search: ''
})
const showDetailDialog = ref(false)
const currentTicket = ref<any>(null)
const showEditDialog = ref(false)
const editTicket = ref<any>(null)
const selectedTickets = ref<any[]>([])
// const showBatchAssign = ref(false)
const showBatchExport = ref(false)
const exportFields = [
  { label: '工单号', value: 'id' },
  { label: '标题', value: 'title' },
  { label: '客户', value: 'customer' },
  { label: '优先级', value: 'priority' },
  { label: '状态', value: 'status' },
  { label: '分配客服', value: 'assignee' },
  { label: '创建时间', value: 'createdAt' }
]

const tickets = ref([...mockTickets])

const filteredTickets = computed(() => {
  let list = tickets.value
  if (filters.value.type) list = list.filter(t => t.type === filters.value.type)
  if (filters.value.priority) list = list.filter(t => t.priority === filters.value.priority)
  if (filters.value.status) list = list.filter(t => t.status === filters.value.status)
  if (filters.value.assignee) list = list.filter(t => t.assignee === filters.value.assignee)
  if (filters.value.search) {
    const s = filters.value.search.trim()
    list = list.filter(t => t.title.includes(s) || t.customer.includes(s))
  }
  // 分页
  const start = (page.value - 1) * pageSize
  return list.slice(start, start + pageSize)
})

function onFilterChange(val: any) {
  filters.value = { ...filters.value, ...val }
  page.value = 1
}
function onViewTicket(ticket: any) {
  currentTicket.value = ticket
  showDetailDialog.value = true
}
function onEditTicket(ticket: any) {
  editTicket.value = { ...ticket }
  showEditDialog.value = true
}
function onDeleteTicket(ticket: any) {
  if (ticket.status === 'closed' || ticket.status === 'resolved') return
  ElMessageBox.confirm('确定要删除该工单吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const idx = tickets.value.findIndex(t => t.id === ticket.id)
    if (idx > -1) tickets.value.splice(idx, 1)
    selectedTickets.value = selectedTickets.value.filter(t => t.id !== ticket.id)
  })
}
function onCreateTicket() {
  editTicket.value = null
  showEditDialog.value = true
}
function onSaveTicket(ticket: any) {
  if (ticket.id) {
    // 编辑，找到并替换
    const idx = tickets.value.findIndex(t => t.id === ticket.id)
    if (idx > -1) tickets.value[idx] = { ...ticket }
  } else {
    // 新建，生成新id
    ticket.id = 'T' + (Math.floor(Math.random() * 1000000) + Date.now())
    ticket.createdAt = new Date().toLocaleString()
    tickets.value.unshift({ ...ticket })
  }
  showEditDialog.value = false
}
function onSelectionChange(selection: any[]) {
  selectedTickets.value = selection
}
// 批量分配客服功能 - 已隐藏
// function onBatchAssign() {
//   showBatchAssign.value = true
// }
// function onBatchAssignConfirm(assignee: string) {
//   selectedTickets.value.forEach(t => {
//     const idx = tickets.value.findIndex(item => item.id === t.id)
//     if (idx > -1) tickets.value[idx] = { ...tickets.value[idx], assignee }
//   })
//   showBatchAssign.value = false
//   selectedTickets.value = []
// }
function onBatchClose() {
  selectedTickets.value.forEach(t => {
    const idx = tickets.value.findIndex(item => item.id === t.id)
    if (idx > -1) tickets.value[idx] = { ...tickets.value[idx], status: 'closed' }
  })
  selectedTickets.value = []
}
function onBatchExport() {
  showBatchExport.value = true
}
function onBatchExportConfirm(fields: string[]) {
  const data = selectedTickets.value.map(t => {
    const row: any = {}
    fields.forEach(f => { row[f] = t[f] })
    return row
  })
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '工单')
  XLSX.writeFile(wb, 'tickets_export.xlsx')
  showBatchExport.value = false
  selectedTickets.value = []
}
</script>

<style scoped>
.ticket-manage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 0;
}
.mb-3 { margin-bottom: 24px; }
.mt-4 { margin-top: 32px; }
.flex { display: flex; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.gap-2 { gap: 8px; }
.text-lg { font-size: 20px; }
.font-bold { font-weight: bold; }
</style>
